Authenticating Login
Credentials First I set up forms
authentication by adding the tags to web.config. Next I
created the login.aspx file, which has little code now.
Now you'll learn how to fill in some of the blanks by
examining actual user authentication.
In the Page_Load
method (in login.aspx shown in Listing 2), compare the username and
password the user enters in the form against
database values.
You start with: |
// authenticate user
if (true) |
You must check the following: |
// authenticate user
if ((username.Value == usernameFromDB) && (password.Value == passwordFromDB)) |
Getting the username and password values from the
form is straightforward: use the Value property. You
obtain the usernameFromDB and passwordFromDB values by using the
Dreamweaver MX DataSet tag. A dataset is a lot like a
recordset: It contains data rows that correspond to
table columns. Use the DataSet tag attributes to specify
what data to collect and how to gather it. You will also
use its methods to access specific pieces of data.
Note: You can learn more about the
DataSet tag from this TechNote: "Using
MM:DataSet."
Next, you'll learn how to create a dataset
in Dreamweaver MX. If you're already familiar
with the Dreamweaver MX user interface,
skip to the section "Creating a Forms Authentication
Ticket Object."
Create the DataSet Tag To create
a DataSet tag, go to the Application panel, click the
Server Behaviors tab, click the plus button and then
select DataSet from the menu:
|
 |
|
(You can also use the Stored Procedure option to
create a dataset. The main difference: the command text
is a stored procedure name rather than a SQL SELECT
statement.)
The DataSet dialog box apears: |
 |
|
In the Connection section, the security connection
should already exist (see Appendix A,
"Site Setup and Database Connection").
You can also define a new connection in
the dialog box. Click the Define button,
which puts you through the the dialog
boxes mentioned in Appendix A. Dreamweaver
MX uses the login information you provided
when you created the connection to access
the database (how convenient!). It builds
the list of tables shown in the Table
pop-up menu and automatically displays
the list of fields for the selected table.
In the Columns section, hold down the Control key to
select more than one column in this menu.
Name
the dataset as you wish (this example uses DS_uidAndPwd ), select the
connection name (this example uses security ) from the pop-up menu and
select the database table (this example uses dbo.members ) from which to get the
data. In this case, select two of the columns by
clicking the Selected radio button; at the same time,
hold down the Control key and select emailaddr and password .
Note: The user's e-mail address
doubles as the username in this example.
Since you do not need to choose a sort order (in SQL,
this is ORDER BY) leave that pop-up menu set to None.
However, you must set up filter criteria select the
database row that matches both the e-mail address and
the password that the user entered on the form. The
simple version of the DataSet dialog allows you to
filter on only one item, so to filter on two columns and
click the Advanced button: |
 |
|
The information you've specified up to this point is
already filled in. To filter the SQL statement, add the
following WHERE clause to the SELECT
statement: |
WHERE emailaddr=@emailaddr AND password=@password |
 |
|
Now you need to define the @emailaddr and @password parameters. Open the Add
Parameter dialog box by clicking the plus button next to
Parameters: |
 |
|
Type the name of the parameter and select the data
type from the Type pop-up menu. Click the Build button
to define the value of the parameter: |
 |
|
In the Build Value dialog box, enter the name of the
form element and select Form Variable from the Source
pop-up menu. You can leave Default Value blank. Click OK
to get back to the Add Parameter dialog box: |
 |
|
Note how the value was built. Dreamweaver adds logic
for you to handle the case of a blank form element. The
ternary operator (so called because it takes three
operands) says to use the form element's value if it
exists; otherwise, use a blank string. If something
besides a blank string works in your application, type
it in the Value box directly. Click OK to close the
dialog box and return to the DataSet dialog box. Notice
that @emailaddr now
appears in the list of parameters. Do the same thing to
define the @password
parameter. Click OK to finish building the
dataset. |
 |
|
Listing 3 shows the code that Dreamweaver
MX writes for the DS_uidAndPwd dataset.
The DS_uidAndPwd
dataset requires one last modification. The command
specified in the CommandText attribute executes
every time the page loads. However, you want the dataset
to execute only if a user submits the form (because it
doesn't make sense to execute the dataset without values
from the form).
To execute only when a user submits the form, use the
Expression attribute: |
<MM:DataSet
id="DS_uidAndPwd"
...
Expression='<%# IsPostBack %>'
> |
The Expression attribute is an optional Boolean value
with a default value of true. If you don't want DataSet
to execute, make sure that Expression evaluates to
false. If you don't want DataSet to execute, make sure
that Expression evaluates to false. In this case, use
the page's IsPostBack
property to determine whether the requested page is due
to a client postback or due to a client accessing the
page for the first time.
In addition to the dataset code given
in Listing 3, Dreamweaver MX writes an
@ Register
directive and an MM:PageBind tag to your
page. The page requires both elements
to compile and run successfully. There's
no need to modify the code that Dreamweaver
MX writes for you; leave it as it is.
The @ Register
directive. The first time you add any
Dreamweaver MX tag to your page, Dreamweaver MX adds
this directive. It tells the compiler where to find the
code for the tags. If this tag is missing a parser error
("Parser Error Message: Unknown server tag
'MM:DataSet'") will appear when you browse the page. The
@ Register directive
defines the Dreamweaver MX controls'
namespace: |
<%@ Register TagPrefix="MM" Namespace="DreamweaverCtrls"
Assembly="DreamweaverCtrls,version=1.0.0.0,publicKeyToken=
836f606ede05d46a,culture=neutral" %> |
The MM:PageBind tag. This
is a declarative form of the Page.DataBind method. In
other words, if you put a MM:PageBind tag on your page,
you generally don't need to worry ever about calling
DataBind within your Page_Load method again. The
MM:PageBind tag code looks like: |
<MM:PageBind runat="server" PostBackBind="true" /> |
Now that you have the dataset, how do you use it?
The DataSet
tag. One of the key points in this
article is using data obtained with the DataSet tag. Use
the DataSet tag to verify the user's login info. If both
the e-mail address and password entered into the form
match what's in the database, then the user has logged
in successfully. Otherwise, the user sees the "Invalid
Credentials" along with the login form.
This is what you started with: |
// authenticate user
if (true) |
This is what you want to check: |
// authenticate user
if ((username.Value == usernameFromDB) &&
(password.Value == passwordFromDB)) |
And this shows you how to use the values in
DataSet: |
// authenticate user
if ((emailaddr.Value == DS_uidAndPwd.FieldValue("emailaddr",null)) &&
(password.Value == DS_uidAndPwd.FieldValue("password",null)))
{
// The user has been authenticated.
}
else
{
Msg.Text = "Invalid Credentials: Please try again";
} |
Because the emailaddr and password form elements use
runat=server , they are
server-side tags and you can access their values in the
Page_Load function
using the Value method.
The values on the right side of the double equal
signs result from the FieldValue method of the
dataset: |
FieldValue(string FieldName, System.Web.UI.Control Container) |
The first argument, FieldName , is the name of the column
in your database table. The second argument
is either the word "Container" or "null."
Use "Container" in cases where you want
the dataset value to be displayed within
a containing control (DataGrid, for example).
Learn more about the DataSet tag and its
methods in Appendix B, "DataSet Tag Methods."
Dreamweaver MX allows you to access the dataset
values through the Application panel's Bindings
tab: |
 |
|
The easiest way to access data from the DataSet tag
is to drag it from the Bindings tab. To get the
emailaddr value, place
your cursor over the value and drag it to your page.
Here's the code on your page: |
<%# DS_uidAndPwd.FieldValue("emailaddr", Container) %> |
This will require minor modifications.
Because you're using the dataset values in the
Page_Load function:
- You don't have a container. Replace "Container"
with "null" to indicate no container.
- You don't need it inside a binding expression.
Remove the
<%# and
%> tags.
Even though you must edit the code a little bit, I
think you'll appreciate the drag-and-drop convenience.
Of course, you can type it all in Code view instead if
you prefer.
The login-2.aspx file included in the download link
shows the page that you've built it so far. It contains
the DataSet tag, @
Register directive, and MM:PageBind tagas
well as using the dataset values in the Page_Load function to authenticate
the user's login credentials
At this point, you have authenticated the user.
Creating a Forms
Authentication Ticket Object with the RedirectFromLoginPage
Method After verifying the user's login
credentials, call the FormsAuthentication.RedirectFromLoginPage
method. This part of login.aspx verifies the user's
login credentials against values in the database
(obtained with the DataSet tag) and, upon successful
login, creates the ticket and redirects the user to the
page they originally requested:
|
// authenticate user
if ((emailaddr.Value == DS_uidAndPwd.FieldValue("emailaddr",null)) &&
(password.Value == DS_uidAndPwd.FieldValue("password",null)))
{
// The user has been authenticated.
FormsAuthentication.RedirectFromLoginPage(emailaddr.Value, false)
}
else
{
Msg.Text = "Invalid Credentials: Please try again";
} |
The FormsAuthentication.RedirectFromLoginPage
method performs these tasks:
- It creates the
FormsAuthenticationTicket .
- It redirects to the originally requested URL or to
default.aspx if the login page was accessed directly.
The authentication ticket creates a cookie, which
becomes part of the HttpResponse object. When a user
requests a page in a restricted folder, the ASP.NET
framework gets the cookie, extracts the ticket, and
determines whether the user is allowed to access the
page. If the cookie doesn't exist or doesn't contain the
right credentials, the page does not allow the user to
view the requested page. The authentication occurs
automatically within RedirectFromLoginPage (even though
the name wouldn't indicate that).
One drawback to this approach is that RedirectFromLoginPage redirects to
default.aspx if there is no originally requested
pagethat is, when users access the login page directly.
This may not be the most convenient or logical page to
which to redirect your site's visitors, however. The
alternativeto redirect explicitlymeans that you cannot
use RedirectFromLoginPage ; instead
you'll have to create your own FormsAuthenticationTicket and
redirect the user appropriately. You'll learn how to
create your own FormsAuthenticationTicket in the
next modification; where you'll allow your
authentication scheme multiple login roles. |
|
|
|